package com.niezhiliang.netty.websocket.spring.boot.demo.utils;


import io.netty.buffer.ByteBuf;
import io.netty.buffer.ByteBufUtil;
import io.netty.buffer.Unpooled;

import java.nio.charset.StandardCharsets;

public class DataUtil {
    public static ByteBuf strToDirectByteBuf(String message){
        if (message==null||message.length()<=0){
            return null;
        }

        // Step 1: Convert the string to a byte array using UTF-8 encoding
        byte[] byteArray = message.getBytes(StandardCharsets.UTF_8);

        // Step 2: Allocate a Direct ByteBuffer with the same size as the byte array
        ByteBuf byteBuf = Unpooled.directBuffer(byteArray.length);


        // Step 3: write the byte array into the Direct ByteBuffer
        byteBuf.writeBytes(byteArray);

        // Now, the string has been safely converted to a Direct ByteBuffer
        // You can perform operations on the directBuffer as needed
        return byteBuf;
    }
}
